﻿using BookmarksDb.Data;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Linq;

namespace BookmarkSimpleSearch
{
    public class SimpleSearchManager
    {
        public static void Main()
        {
            string xmlPath = @"../../../../Resources/simple-search-queries.xml";

            Search(xmlPath);
        }

        private static void Search(string xmlPath)
        {
            XmlReader reader = XmlReader.Create(xmlPath);

            using (reader)
            {
                bool hasQuery = false;
                string username = string.Empty;
                string tag = string.Empty;

                while (reader.Read())
                {
                    if (reader.Name == "query" && hasQuery)
                    {
                        if (tag == string.Empty)
                        {
                            throw new ArgumentException("The tag must be declared and it is mandatory!");
                        }

                        List<Bookmark> bookmarks = ExecuteDatabaseSearch(username, tag);
                        PrintResultsOnConsole(bookmarks);

                        username = string.Empty;
                        tag = string.Empty;

                        hasQuery = false;
                    }
                    else if (reader.Name == "username")
                    {
                        username = reader.ReadElementString();
                        hasQuery = true;
                    }
                    else if (reader.Name == "tag")
                    {
                        tag = reader.ReadElementString();
                        hasQuery = true;
                    }
                }
            }
        }

        private static List<Bookmark> ExecuteDatabaseSearch(string username, string tag)
        {
            using (var context = new BookmarksDBEntities())
            {
                var bookmarks = context.Bookmarks.Include("User").Include("Tags").Where(x => x.Tags.Any(t => t.Name == tag));
                if (username != string.Empty)
                {
                    bookmarks = bookmarks.Where(x => x.User.Username == username);
                }

                List<Bookmark> result = bookmarks.OrderBy(x => x.URL).ToList();

                return result;
            }
        }

        private static void PrintResultsOnConsole(List<Bookmark> bookmarks)
        {
            if (bookmarks.Count == 0)
            {
                Console.WriteLine("Nothing found");
                return;
            }

            StringBuilder result = new StringBuilder();

            foreach (var bookmark in bookmarks)
            {
                result.AppendLine(bookmark.URL);
            }

            Console.WriteLine(result.ToString());
        }
    }
}
